package com.happyscan138.makefun;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.adapter.chatAdapter;
import com.happyscan138.makefun.base.AudioRecorderButton;
import com.happyscan138.makefun.base.MediaPlayerManager;
import com.happyscan138.makefun.model.ChatMessage;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.R.layout.chat;
import static com.happyscan138.makefun.Urls.Urls.ChatImg;
import static com.happyscan138.makefun.Urls.Urls.base;
import static com.happyscan138.makefun.base.Uri.getPhotoPathFromContentUri;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/20.
 */

public class Chat extends AppCompatActivity implements View.OnClickListener, AbsListView.OnScrollListener {
    private ListView chat_listView;
    private List<ChatMessage> listviewData;
    private Button plus_image,plus_video;
    private ImageButton back;
    private Button buttonSend;
    private LinearLayout plus_linearlayout,panel_root;
    private EditText sendText;
    private String message_send,user_id;
    private SharedPreferences preferences;
    private String accessy_ley;
    private TextView Username;
    private String myselfId;
    private ChatMessage dataMessage;
    private Intent intent;
    private chatAdapter adapter;
    private String mySelfHead;
    private String VideoPath;
    private ImageButton Voice0rKey;
    private boolean btn_vocie = false;
    private AudioRecorderButton press_text;
    private View animView;
    private String myHead;
    private final int SUCCESS=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(chat);
        initView();
        preferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        accessy_ley=preferences.getString("UserId","");
        myselfId=preferences.getString("user_id","");
        client=new AsyncHttpClient();
        params=new RequestParams();
        params.put("access_key",accessy_ley);
        intent=getIntent();
        //user_id不是自己的ID，而是当前对话聊天对方的ID
        user_id=intent.getStringExtra("user_id");
        log.e("Makeservice",user_id);
        params.put("send_u_id",user_id);
        params.put("page_count",50);
        params.put("msg_id_index",0);
        log.e("paramsChat",params.toString());
        RequestHandle handleList=client.post(Urls.MessageList,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr=response.toString();
                log.e("chatJsonStr",jsonStr);
                listviewData=new ArrayList<>();
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    JSONObject data=jsonObject.getJSONObject("data");
                    JSONObject user=data.getJSONObject("userList");
                    JSONObject with=user.getJSONObject(user_id);
                    JSONObject myself=user.getJSONObject(myselfId);
                    String UserName=with.getString("nick_name");
                    Username.setText(UserName);
                    log.e("with",with.toString());
                    JSONArray jsonArray=data.getJSONArray("msgList");
                    for (int i=0;i<jsonArray.length();i++){
                        dataMessage=new ChatMessage();
                        JSONObject listData=jsonArray.getJSONObject(i);
                        dataMessage.content=listData.getString("msg");
                        dataMessage.left_head=base+with.getString("img_path");
                        dataMessage.right_head=base+myself.getString("img_path");
                        myHead=dataMessage.right_head;
                        dataMessage.mongo = ChatImg + "access_key=" + accessy_ley + "&" + "mongo_resource_id=" + listData.getString("mongo_resource_id");
                        log.e("dataMessage.mongo",dataMessage.mongo);
                        dataMessage.thumb_resource=base+listData.getString("thumb_resource");
                        mySelfHead=dataMessage.right_head;
                        dataMessage.msg_type=listData.getInt("msg_type");
                        int send_user_id=listData.getInt("send_u_id");
                        int TagUserID=Integer.valueOf(myselfId);
                        listviewData.add(dataMessage);
//                        log.e("imageViewChat",listviewData.get(i).mongo);
                        /*send_user_id发送消息的用户id，
                        TagUserID是自己的id，
                        如果send_user_id==TagUserID就是在右边的布局，再根据msg_type确定布局的类型
                         */
                        if(send_user_id==TagUserID&&dataMessage.msg_type==1){
                            dataMessage.setType(ChatMessage.TYPE_SEND);
                        }else if(send_user_id!=TagUserID&&dataMessage.msg_type==1){
                            dataMessage.setType(ChatMessage.TYPE_RESPONSE);
                        }else if(send_user_id==TagUserID&&dataMessage.msg_type==2){
                            dataMessage.setType(ChatMessage.TYPE_SEND_IMAGE);
                        }else if(send_user_id!=TagUserID&&dataMessage.msg_type==2){
                            dataMessage.setType(ChatMessage.TYPE_RESPONCE_IMG);
                        }else if(send_user_id==TagUserID&&dataMessage.msg_type==3){
                            dataMessage.setType(ChatMessage.TYPE_SEND_VIDEO);
                        }else if(send_user_id!=TagUserID&&dataMessage.msg_type==3){
                            dataMessage.setType(ChatMessage.TYPE_RESPONCE_VIDEO);
                        }else if(send_user_id==TagUserID&&dataMessage.msg_type==4){
                            dataMessage.setType(ChatMessage.TYPE_SEND_VOICE);
                        }
                    }

                    Collections.reverse(listviewData); // 倒序排列
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter=new chatAdapter(Chat.this,listviewData,accessy_ley);
                chat_listView.setAdapter(adapter);
                chat_listView.setSelection(listviewData.size());

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });


    }


    public void initView(){
        TextChange change=new TextChange();
        chat_listView=(ListView)findViewById(R.id.talk_listview);
        chat_listView.setOnScrollListener(this);
//        chat_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (animView != null) {
//                    animView.setBackgroundResource(R.mipmap.adj);
//                    animView = null;
//                }
//                animView = view.findViewById(R.id.id_recoder_anim);
//                animView.setBackgroundResource(R.drawable.play_anim);
//                AnimationDrawable animation = (AnimationDrawable) animView.getBackground();
//                animation.start();
//                // 播放录音
//                log.e("voice",listviewData.get(position).mongo);
//                MediaPlayerManager.playSound(listviewData.get(position).mongo, new MediaPlayer.OnCompletionListener() {
//
//                    public void onCompletion(MediaPlayer mp) {
//                        //播放完成后修改图片
//                        animView.setBackgroundResource(R.mipmap.adj);
//                    }
//                });
//            }
//        });
        plus_image=(Button)findViewById(R.id.plus_image);
        plus_image.setOnClickListener(this);
        buttonSend=(Button)findViewById(R.id.button_send);
        buttonSend.setOnClickListener(this);
        plus_linearlayout=(LinearLayout)findViewById(R.id.input_linearlayout);
        back=(ImageButton)findViewById(R.id.chat_back);
        back.setOnClickListener(this);
        sendText=(EditText)findViewById(R.id.message_send);
        sendText.addTextChangedListener(change);
        Username=(TextView)findViewById(R.id.chat_user);
        panel_root=(LinearLayout)findViewById(R.id.panel_root);
        plus_video=(Button)findViewById(R.id.chat_video);
        plus_video.setOnClickListener(this);
        Voice0rKey=(ImageButton)findViewById(R.id.voice_or_keyword);
        Voice0rKey.setOnClickListener(this);
        press_text=(AudioRecorderButton)findViewById(R.id.press_long);
        //长按录音
        press_text.setFinishRecorderCallBack(new AudioRecorderButton.AudioFinishRecorderCallBack(){

            @Override
            public void onFinish(float seconds, String filePath) {
                ChatMessage recorder=new ChatMessage(seconds, filePath,myHead);
                log.e("seconds",myHead);
                log.e("seconds",seconds+"");
                log.e("secondspath",filePath);
                recorder.setType(ChatMessage.TYPE_SEND_VOICE);
                listviewData.add(recorder);
                adapter.notifyDataSetChanged();
                chat_listView.setSelection(listviewData.size());

                params=new RequestParams();
                params.put("access_key",accessy_ley);
                params.put("receive_u_id", user_id);
                params.put("msg_type", 4);
                File file=new File(filePath);
                try {
                    params.put("file", file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                RequestHandle handle = client.post(Urls.SendMessage, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        log.e("onSuccess", jsonStr);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                    }
                });
            }
        });

    }






    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.chat_back:
                finish();
                break;
            case R.id.button_send:
                if(message_send!=null){
                    params=new RequestParams();
                    ChatMessage msg = new ChatMessage( message_send,ChatMessage.TYPE_SEND);
                    log.e("message_send",message_send);
                    msg.right_head=mySelfHead;
                    listviewData.add(msg);
                    adapter.notifyDataSetChanged();
                    chat_listView.setSelection(listviewData.size());
                    params.put("access_key",accessy_ley);
                    params.put("receive_u_id", user_id);
                    params.put("msg", message_send);
                    log.e("parameSendMsg", params.toString());
                    RequestHandle handle = client.post(Urls.SendMessage, params, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            String jsonStr = response.toString();
                            log.e("onSuccess", jsonStr);
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            super.onFailure(statusCode, headers, responseString, throwable);
                        }
                    });
                    sendText.setText(null);
                }else
                    buttonSend.setClickable(false);


                break;
            case R.id.plus_image:
                if(panel_root.getVisibility()==View.GONE){
                    panel_root.setVisibility(View.VISIBLE);
                    Button ChatImg=(Button)findViewById(R.id.chat_img);
                    ChatImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            PhotoPickerIntent intent = new PhotoPickerIntent(Chat.this);
                            intent.setSelectModel(SelectModel.MULTI);
                            intent.setShowCarema(true); // 是否显示拍照， 默认false
                            intent.setMaxTotal(9); // 最多选择照片数量，默认为9
                            //intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                            // intent.setImageConfig(config);
                            startActivityForResult(intent, 001);
                        }
                    });
                }else {
                    panel_root.setVisibility(View.GONE);
                }

                break;
            case R.id.chat_video:
                intent=new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,003);
                break;
            case R.id.voice_or_keyword:
                if(btn_vocie){
                    btn_vocie = false;
                    Voice0rKey.setBackgroundResource(R.mipmap.voice);
                    press_text.setVisibility(View.VISIBLE);
                    sendText.setVisibility(View.GONE);
                }else {
                    Voice0rKey.setBackgroundResource(R.mipmap.chat_keyword);
                    press_text.setVisibility(View.GONE);
                    sendText.setVisibility(View.VISIBLE);
                    btn_vocie = true;
                }
                break;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            //投掷状态
            case SCROLL_STATE_FLING:

                break;
            //闲置状态
            case SCROLL_STATE_IDLE:

                break;
            //滑动状态
            case SCROLL_STATE_TOUCH_SCROLL:
               log.e("TYPE_TO_USER_IMG","sssssssssssssssssssss");
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    //EditText的监听器
    private class TextChange implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count==0){
                buttonSend.setClickable(false);
                buttonSend.setBackgroundResource(R.drawable.send_message_enable);
            }else {
                buttonSend.setBackgroundResource(R.drawable.send_message_disable);
                buttonSend.setClickable(true);
            }

        }
        @Override
        public void afterTextChanged(Editable s) {
            message_send =sendText.getText().toString();

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
     if(resultCode==RESULT_OK){
         switch (requestCode){
            case 001:
                log.e("paths","path");
                refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                break;
         }
      }
        if (requestCode == 003 && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri=data.getData();
            VideoPath=getPhotoPathFromContentUri(this,uri);
            ChatMessage msg = new ChatMessage( ChatMessage.TYPE_SEND_VIDEO,VideoPath);
            msg.right_head=mySelfHead;
            listviewData.add(msg);
            adapter.notifyDataSetChanged();
            chat_listView.setSelection(listviewData.size());
            params=new RequestParams();
            params.put("access_key",accessy_ley);
            params.put("receive_u_id", user_id);
            params.put("msg_type", 3);
            File file=new File(VideoPath);
            try {
                params.put("file", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            RequestHandle handle = client.post(Urls.SendMessage, params, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    String jsonStr = response.toString();
                    log.e("onSuccess", jsonStr);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                }
            });
        }


    }
    private void refreshAdpater(ArrayList<String> paths){
        for (int i=0;i<paths.size();i++){
            String path=paths.get(i);
            ChatMessage msg = new ChatMessage( ChatMessage.TYPE_SEND_IMAGE,path);
            msg.right_head=mySelfHead;
            listviewData.add(msg);
            adapter.notifyDataSetChanged();
            chat_listView.setSelection(listviewData.size());
            params=new RequestParams();
            params.put("access_key",accessy_ley);
            params.put("receive_u_id", user_id);
            params.put("msg_type", 2);
            File file=new File(path);
            try {
                params.put("file", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            client.post(Urls.SendMessage, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                        }

                        @Override
                        public void onProgress(long bytesWritten, long totalSize) {
                            super.onProgress(bytesWritten, totalSize);
                            int count=(int)((bytesWritten*1.0/totalSize)*100);

                            adapter.setImgCount(count);
                            adapter.notifyDataSetChanged();
                           // adapter.notifyDataSetChanged();
                        }
                    }
            );
            log.e("paths",path);
        }
        // 处理返回照片地址

    }
    @Override
    protected void onPause() {
        super.onPause();
        MediaPlayerManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaPlayerManager.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaPlayerManager.release();
    }
}